import traceback

from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.status import HTTP_500_INTERNAL_SERVER_ERROR

from programApi.exercise.exerciese_models import ExerciseHistory, ExerciseContent
from programApi.exercise.exercise_serializers import ExerciseHistorySerializer

"""
    @url('/exercise/')
"""


class ExerciseViewSet(viewsets.ViewSet):

    def list(self, request):
        """
        练习exercise_viewset 的 get method
        @param request:
        ?type=history => 查询用户答题历史
        ?type=exercise => 获取题目内容
        @return:
        """
        serializer = None
        try:
            params = self.request.query_params
            todo = params.get('type')
            # 处理返回用户答题历史
            if todo == 'history':
                openid = params.get('openid')
                queryset = ExerciseHistory.objects.filter(userId=openid)
                serializer = ExerciseHistorySerializer(queryset, many=True)
                return Response(serializer.data)
            # 处理获取题目内容，目前为全返回
            elif todo == 'exercise':
                queryset = ExerciseContent.objects.all()
                a_list = []
                # 重新封装返回对象
                for i in queryset:
                    dict = {'options': [{'id': 'A', 'name': i.optionA}, {'id': 'B', 'name': i.optionB},
                                        {'id': 'C', 'name': i.optionC}, {'id': 'D', 'name': i.optionD}, ]}
                    a_list.append({'exerciseContent': i.exerciseContent, 'options': dict, 'answer': i.exerciseAnswer})
                result = {'size': len(queryset), 'exerciseList': a_list}
                return Response(data=result)
        except Exception as e:
            traceback.print_exc()
        return Response(status=HTTP_500_INTERNAL_SERVER_ERROR)

    def create(self, request):
        """
        练习exercise_viewset 的 post method
        插入一条用户答题记录
        @param request:
        userChosen : 用户选择的答案
        exerciseAnswer : 正确答案
        exerciseContent : 练习题内容
        userId : 用户Id
        @return:
        """
        print(request.data)
        data = request.data
        serializer = ExerciseHistorySerializer(
            data={'userChosen': data.get('userChosen'), 'exerciseAnswer': data.get('exerciseAnswer'),
                  'exerciseContent': data.get('exerciseContent'), 'userId': data.get('id')})
        # 验证数据 并保存
        if serializer.is_valid():
            print(serializer.validated_data)
            serializer.save()
        else:
            return Response(status=HTTP_500_INTERNAL_SERVER_ERROR)
        return Response()
